#!/usr/bin/env python3
import sys
import os
import json
from io import FileIO, StringIO
import threading


class Android:

    def __init__(self):
        self.list = []

    def convert(self, raw):
        for p in raw:
            self.list.append(self.__gen_province(p))

    def __gen_province(self, raw_province):
        province_template = dict(Name='', City=[])
        province_template['Name'] = raw_province.get('p')
        for c in raw_province.get('c', []):
            province_template['City'].append(self.__gen_city(c))
        return province_template

    def __gen_city(self, raw_city):
        city_template = dict(Name='', Area=[])
        city_template['Name'] = raw_city.get('n')
        for a in raw_city.get('a', []):
            city_template['Area'].append(self.__gen_area(a))
        return city_template

    def __gen_area(self, raw_area):
        area_template = dict(Name='')
        area_template['Name'] = raw_area.get('s')
        return area_template

    @property
    def content(self):
        return self.list


class IOS:

    def __init__(self):
        self.list = []

    def convert(self, raw):
        for p in raw:
            self.list.append(self.__gen_state(p))

    def __gen_state(self, province):
        state = dict(cities=[], state='')
        state['state'] = province.get('p')
        for c in province.get('c', []):
            state['cities'].append(self.__gen_city(c))
        return state

    def __gen_city(self, city):
        city_t = dict(areas=[], city='')
        city_t['city'] = city.get('n')
        for a in city.get('a', []):
            city_t['areas'].append(self.__gen_street(a))
        return city_t

    def __gen_street(self, area):
        county = dict(streets=[], county='')
        county['county'] = area.get('s')
        return county

    @property
    def content(self):
        return self.list


PLATFORM = {"android": Android, "ios": IOS }


def convert(raw, platform):
    converter = PLATFORM.get(platform, 'android')()
    print('{0} 转换开始...'.format(platform))
    converter.convert(area)
    result = json.dumps(converter.content, ensure_ascii=False)
    FileIO('./{0}_area.json'.format(platform), 'w').write(bytes(result, 'utf-8'))
    if platform == 'ios':
        os.system('swift ./convert.swift')
    print('{0} 转换完成.'.format(platform))

if __name__ == "__main__":
    if len(sys.argv) > 1:
        path = sys.argv[1]
    else:
        path = './area.json'
    try:
        area = json.load(FileIO(path, 'r'))
        print('convert area start...')
        android_thread = threading.Thread(target=convert, args=(area, 'android'))
        ios_thread = threading.Thread(target=convert, args=(area, 'ios'))
        android_thread.run()
        ios_thread.run()
        print('done.')
    except FileNotFoundError:
        print("\033[31m[ERROR] 没有找到文件：{0}\033[0m".format(path))
        exit(-1)
    except RuntimeError as err:
        print("\033[31m[ERROR] {0}\033[0m".format(err))
        exit(-1)
